package com.example.tcp.client.store.impl;

import com.example.tcp.client.RetryTcpClient;
import com.example.tcp.client.store.AbstractDequeStore;
import com.squareup.tape2.ObjectQueue;
import com.squareup.tape2.QueueFile;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class Tap2FileQueueDequeStore<T> extends AbstractDequeStore<T> {

    private ObjectQueue<T> queue;

    public Tap2FileQueueDequeStore(String filename, ObjectQueue.Converter<T> converter) throws IOException {
        this.queue = ObjectQueue.create(new QueueFile.Builder(new File(filename)).build(), converter);
    }

    @Override
    protected boolean _enqueue(T e) {
        try {
            this.queue.add(e);
            return true;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected T _dequeue() {
        T e = null;
        try {
            e = queue.peek();
            if(e != null) {
                queue.remove();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return e;
    }

    @Override
    protected void _close() {
        try {
            queue.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isEmpty() {
        return queue.isEmpty();
    }

    @Override
    public Object wrap() {
        return queue;
    }

    @Override
    public T peek() {
        try {
            return queue.peek();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long size() {
        return queue.size();
    }
}
